package leetcode.Y2024M5D27;

import org.junit.Test;

import java.util.*;

public class S71 {
    public String simplifyPath(String path) {
        // 使用split将path分隔，对于 .. 执行pop操作，如果不是.就执行入栈操作
        Deque<String> stack=new LinkedList<>();
        for (String e : path.split("/")) {
            if (e.equals("..")){
                if (!stack.isEmpty()){
                    stack.pop();
                }
            }else if (!e.isEmpty()&&!e.equals(".")){
                stack.push(e);
            }
        }
        StringBuilder builder=new StringBuilder();
        Iterator<String> iterator = stack.descendingIterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            builder.append("/"+next);
        }
        return builder.length()==0?"/":builder.toString();
    }

    @Test
    public void test() {
        String path = "/home/";
        System.out.println(simplifyPath(path));

    }

    @Test
    public void test1() {
        String path = "/../";
        System.out.println(simplifyPath(path));
    }

    @Test
    public void test2() {
        String path = "/a/./b/../../c/";
        System.out.println(simplifyPath(path));
    }
}
